package com.dchh.android.suverynew.act;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.LevelSelectAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.views.LevelOperateWindow;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.Action;
import com.dhcc.android.base.common.bean.Check;
import com.dhcc.android.base.common.bean.Node;
import com.dhcc.android.base.common.view.MyLoadingDialog;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.gis.DataController;
import com.dhcc.android.base.gis.FactoryGPS;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import srs.GPS.GPSConvert;
import srs.Geometry.Envelope;
import srs.Geometry.FormatConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Layer.IFeatureLayer;
import srs.Layer.ILayer;
import srs.tools.MapControl;

/**
 * 层级选择
 *
 * @author zhoudan
 * @date 2015年12月29日
 */
public class MapSelectActivity extends SBaseActivity {
    public static final int LOADMAPTYPE = 1;
    /**
     * 层级目录
     */
    private TextView title;//
    /**
     * 层级选择目录布局
     */
    private LinearLayout titleLayout;
    /**
     * 地图布局
     */
    private LinearLayout map;

    /**
     * 显示GPS信息
     */
    private TextView tv_GPSinfo = null;

    /**
     * 图层
     */
    private ILayer targetLayer = null;

    private LinearLayout selectListLayout;

    private ListView selectListview;

    private TextView selectClose;

    /**
     * 指南针
     */
    private LinearLayout zhinanzhen;
    /**
     * 无人机
     */
    private LinearLayout wurenji;

    /**
     * 导航
     */
    private RelativeLayout nav;
    /**
     * 任务包路径
     */
    private String root;

    /**
     * 导航名称
     */
    private String navName;
    /**
     * 任务名称
     */
    private String taskName;


    //选择列表的数据
    /**
     * 层级列表格式化数据
     */
    private List<Map<String, String>> levelList = new ArrayList<Map<String, String>>();
    /**
     * 原始数据
     */
    private List<Map<String, String>> dataList = null;

    private LevelSelectAdapter adapter;

    //层级  上下级跳转变量
    /**
     * 层级节点
     */
    private Node node = null;
    /**
     * 当前层级索引
     */
    private int index = 0;
    /**
     * 当前层级 layer
     */
    private String layer;
    /**
     * 上一层级 layer
     */
    private String pLayer = ""; // 上一层级 layer
    /**
     * 当前层级数据索引
     */
    private int position = -1;
    /**
     * 上一 层级
     */
    private Map<String, String> parent = null;
    /**
     * 当前选择的层级
     */
    private Map<String, String> select;
    /**
     * 层级下标
     */
    private ArrayList<Integer> indexsOfSelected = new ArrayList<Integer>();

    private String periodCode, periodLabel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.task_level_select);
    }

    OnClickListener viewClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.common_nav) {
                selectListLayout.setVisibility(View.VISIBLE);
            } else if (v.getId() == R.id.close) {
                selectListLayout.setVisibility(View.GONE);
            }
        }
    };

    /**
     * 保存选择，为恢复做准备
     */
    private void savaMark() {
        // 保存信息
        SPreferencesManager.saveValue(MSApplication.USERNAME, Constants.USERNAME);
        SPreferencesManager.saveValue(MSApplication.PASSWORD, Constants.PASSWORD);
        SPreferencesManager.saveValue(MSApplication.PERIOD_CODE,
                Constants.currentCycle.getCode());
        SPreferencesManager.saveValue(MSApplication.PERIOD_LABEL,
                Constants.currentCycle.getLabel());
        SPreferencesManager.saveValue(MSApplication.TABLE_CODE,
                Constants.currentTable.getCode());
        SPreferencesManager.saveValue(MSApplication.TABLE_LABEL,
                Constants.currentTable.getLabel());
        SPreferencesManager.saveValue(MSApplication.TASK, taskName);
        SPreferencesManager.saveValue(MSApplication.EXCEPTION_FLAG, false);
    }


    /**
     * 导航按钮可见性设置,无人机按钮的可见性
     */
    private void navShow() {
        if (index == 1) {
            wurenji.setVisibility(View.VISIBLE);
        } else {
            wurenji.setVisibility(View.GONE);
        }
    }

    private void getView() {
        //获取视图组件
        title = (TextView) findViewById(R.id.common_title);
        title.setText(taskName);
        titleLayout = (LinearLayout) findViewById(R.id.common_nav);
        map = (LinearLayout) findViewById(R.id.common_map);
        selectListLayout = (LinearLayout) findViewById(R.id.select_list_layout);
        selectListview = (ListView) findViewById(R.id.select_listview);
        selectClose = (TextView) findViewById(R.id.close);
        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(Constants.screenWidth / 3, RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rl.leftMargin = 10;
        selectListLayout.setLayoutParams(rl);
        //设置列表点选监听
        selectListview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                itemSelected(position, false);
            }
        });

        if (adapter == null) {
            adapter = new LevelSelectAdapter(this, levelList);
            selectListview.setAdapter(adapter);
        }
        selectListLayout.setVisibility(View.GONE);

        titleLayout.setOnClickListener(viewClick);
        selectClose.setOnClickListener(viewClick);

        zhinanzhen = (LinearLayout) findViewById(R.id.zhinanzhen_operate);
        zhinanzhen.setVisibility(View.VISIBLE);
        zhinanzhen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapSelectActivity.this, CompassActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });

        wurenji = (LinearLayout) findViewById(R.id.wurenji_operate);
        wurenji.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MapSelectActivity.this, RandomPhotoActivity.class);
                intent.putExtra("CUNDM", select.get("CUNDM"));
                intent.putExtra("CUNMC", select.get("CUNMC"));
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });
    }

    /**
     * 地图初始
     */
    private void mapView() {
        getData();
        // 刷新列表数据
        adapter.setSelect(-1);
        adapter.refresh(levelList);
        // 地图初始化
        try {
            targetLayer = CommenUtil.loadMap(this, map, root + "/" + taskName, indexsOfSelected, LOADMAPTYPE);
            // 缓存图层缩放范围
            Constants.envelopes.put(index, targetLayer.getExtent());
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "地图渲染出错，请联系管理员", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 列表或者地图点选
     *
     * @param position 选中的item索引
     * @param isMap    是否为地图点选
     */
    public void itemSelected(int position, boolean isMap) {
        //进度框
        Constants.DIALOG = MyLoadingDialog.createLoadingDialog(MapSelectActivity.this, "正在载入，请稍后...");
        Constants.DIALOG.show();

        //改变选中item的样式
        adapter.setSelect(position);
        adapter.notifyDataSetChanged();

        //获取fid
        Integer fid = -1;
        if (isMap) { // 地图点选
            if (CommenUtil.IsListSelected) {
                fid = indexsOfSelected.get(position);
            } else {
                fid = position;
                position = indexsOfSelected.indexOf(fid);
            }
        } else {// 列表点选
            fid = indexsOfSelected.get(position);
        }
        final int pos = position;
        final Integer nfid = fid;

        // 获取当前层级对应的操作
        List<Action> actions = node.getActions();
        // 如果没有操作，直接进入下一级
        if (actions == null || actions.size() == 0) {

            selectListLayout.setVisibility(View.GONE);
            goToNext(position, fid);
        } else { //有操作，显示操作
            wurenji.setVisibility(View.GONE);

            Constants.select = dataList.get(position);

            // 显示操作菜单
            final LevelOperateWindow opw = new LevelOperateWindow(this, actions);
            opw.show(titleLayout, new LevelOperateWindow.OnOpClickListener() {

                @Override
                public void onOpClick(String key) {
                    if (key.equals("000")) { // 下一级
                        selectListLayout.setVisibility(View.GONE);
                        goToNext(pos, nfid);
                    } else if (key.equals("101")) { // 实地采集

                        Constants.DIALOG = MyLoadingDialog.createLoadingDialog(MapSelectActivity.this, "正在载入，请稍后...");
                        Constants.DIALOG.show();
                        if (Constants.clickFlag) {
                            Constants.clickFlag = false;
                            // 获取选中的节点的原始数据
                            final Map<String, String> data = dataList.get(pos);
                            final String yfbh = levelList.get(pos).get("name");
                            final String nt = title.getText() + " > 样方" + yfbh;

                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {

                                    //初始化地块数据
                                    initDkDatas(data.get("YFBHU"));

                                    Intent intent = new Intent(MapSelectActivity.this, DKSelectActivity.class);
                                    intent.putExtra("pvalue", data.get("YFBHU"));
                                    intent.putExtra("navtitle", nt);
                                    intent.putExtra("yfbh", yfbh);
                                    intent.putExtra("taskName", taskName);
                                    startActivity(intent);
                                    Constants.clickFlag = true;
                                }
                            }, 200);
                        }
                    } else if (key.equals("102")) { // 无人机
                        if (readFile()) {
//                            GlobalDataManager.setMap(CommenUtil.getMap());
//                            GlobalDataManager.setFlightTarget(Constants.geometry);
//                            Intent intent = new Intent();
//                            intent.setClass(MapSelectActivity.this, MainActivity.class);
//                            startActivity(intent);
//                            overridePendingTransition(R.anim.push_right_in,
//                                    R.anim.push_left_out);
                        }
                    } else if (key.equals("103")) { // 工具箱

                    } else if (key.equals("201")) { // 高德导航
                        // 导航
                        Intent gpsNaviIntent = new Intent(MapSelectActivity.this, NaviMainActivity.class);
                        gpsNaviIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        startActivity(gpsNaviIntent);
                    }
                    opw.dismiss();
                }
            });


            //===================地图处理===============================

            select = dataList.get(position);
            Constants.select = dataList.get(position);
            Constants.selects.add(index, select);

            // 放大地图
            IFeatureLayer targetLayer_testILayer = DataController.getInstance()
                    .getLayer(Constants.nodelist.get(index).getLayer());
            IEnvelope ev = CommenUtil.setZoomto(fid, targetLayer_testILayer);

            try {
                Constants.geometrys.clear();
                Constants.geometrys.add(targetLayer_testILayer
                        .getFeatureClass().getGeometry(fid));
                Constants.geometry = targetLayer_testILayer.getFeatureClass()
                        .getGeometry(fid);
            } catch (IOException e2) {
                e2.printStackTrace();
            }

            // 保存点击的位置，作为导航目标点用
            try {
                IPoint pointCenter = ((IFeatureLayer) targetLayer_testILayer)
                        .getFeatureClass().getGeometry(fid).CenterPoint();
                if (CommenUtil.IsListSelected) {
                    Constants.TargetXY = GPSConvert.PROJECT2GEO(
                            pointCenter.X(), pointCenter.Y(), CommenUtil
                                    .getMap().getGeoProjectType());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            //设置高亮区域
            try {
                IPoint centerPoint = Constants.TargetPointTouch;
                CommenUtil.setLightSelected(targetLayer_testILayer, fid,
                        (MapControl) CommenUtil.getMapControl(), centerPoint);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            // 地图都处理完最后刷一下就可以了
            CommenUtil.Refresh();
            Constants.dkBack = true;
            //====================地图处理【完】==============================

        }


        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                StringUtil.dismissDialog(Constants.DIALOG);
            }
        }, 500);

    }


    /**
     * 初始化样方中的自然地块数据
     */
    private void initDkDatas(String val) {
        System.out.println("--初始化样方对应的自然地块数据---:" + periodLabel);
        //获取已经存在的数据
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);
        int count = DBImportUtil.count(table, "YFBHU='" + val + "'");
        if (count == 0) {//没有数据
            List<Map<String, String>> datas = CommenUtil.getDataFromShp(root + "/" + taskName + "/" + "TASK/TRANSPORT/样方自然地块.shp", "YFBHU='" + val + "'");
            DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
            DBImportUtil.add(datas, table);
            System.out.println("-----样方自然地块数据：" + datas.size());
        }
        //	    initGeosAndDisdisplayLableNames(val);
    }


    /**
     * 获取样方自然地块的GEOS，rowid，然后填充到Constants.geometrys
     *
     * @param val 样方编号
     * @return
     */
    private void initGeosAndDisdisplayLableNames(String val) {
        DBImportUtil.openDatabase(root, taskName, "/TASK/TRANSPORT/DATA.db");
        String table = CommenUtil.getTableName("样方自然地块", periodLabel);

        String[] str = {"GEO", "rowid"};

        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "YFBHU", val);

        Constants.displayLableNames.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        System.out.println("-----------" + wkt);
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("rowid");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取数据
     */
    private void getData() {
        // 取到配置文件中当前层级的节点
        node = Constants.nodelist.get(index);
        Check check = node.getCheck();
        layer = node.getLayer();


        // 获取数据库中当前层级的下级数据列表
        String[] fields = {node.getFeild(), node.getItem().getFeild(), "rowid"};
        try {
            DBImportUtil.openDatabase(root, taskName, "/TASK/DATA.db");
            if (check == null) {
                dataList = DBImportUtil.listData(node.getTable(), fields, null, null);
            } else {
                String fld = check.getPfeild().toUpperCase();
                String value = parent.get(fld);
                dataList = DBImportUtil.listData(node.getTable(), fields, check.getFeild(), value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "操作外部数据库出错", Toast.LENGTH_SHORT).show();
        }

        // 格式化原始数据
        levelList.removeAll(levelList);
        indexsOfSelected.removeAll(indexsOfSelected);
        int fid = -1;
        for (Map<String, String> map : dataList) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("id", map.get(node.getFeild()));
            String v = map.get(node.getItem().getFeild());
            m.put("name", v);

            // 顺序号要用rowid这一列,rowid要减一，因为从rowid是从1开始，FID从0开始
            fid = Integer.parseInt(map.get("rowid")) - 1;
            m.put("rowid", String.valueOf(fid));
            map.put("rowid", String.valueOf(fid));

            levelList.add(m);
            // 顺序号要用rowid这一列
            indexsOfSelected.add(fid);
        }
    }


    /**
     * 跳转至下一个层级
     */
    private void goToNext(int position, int fid) {

        // 刷新数据
        select = dataList.get(position);
        Constants.selects.add(index, select);
        Constants.players.add(index + 1, layer);
        Constants.positons.add(index + 1, position);

        this.pLayer = layer;
        this.position = position;
        this.parent = select;
        index += 1;

        String s = select.get(node.getItem().getFeild());
        navName += " > " + s;
        title.setText(navName);
        setTitle(select.get(node.getItem().getFeild()));

        getData();
        adapter.setSelect(-1);
        adapter.refresh(levelList);

        //==================地图处理========================
        // 放大地图
        IFeatureLayer nextLayer = DataController.getInstance().getLayer(
                this.pLayer);
        IEnvelope ev = CommenUtil.setZoomto(fid, nextLayer);
        Constants.envelopes.put(index, ev);// 保存当前地图

        // 保存点击的位置，座位导航目标点选
        // add by 李忠义
        try {
            IPoint pointCenter = ((IFeatureLayer) nextLayer).getFeatureClass()
                    .getGeometry(fid).CenterPoint();
            if (CommenUtil.IsListSelected) {
                Constants.TargetXY = GPSConvert.PROJECT2GEO(pointCenter.X(),
                        pointCenter.Y(), CommenUtil.getMap()
                                .getGeoProjectType());
            }
            Constants.targets.put(index, Constants.TargetXY[0] + ","
                    + Constants.TargetXY[1]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置高亮区域
        try {
            IPoint centerPoint = null;
            if (CommenUtil.IsListSelected) {
                centerPoint = nextLayer.getFeatureClass().getGeometry(fid)
                        .CenterPoint();
            } else {
                centerPoint = Constants.TargetPointTouch;
            }
            CommenUtil.setLightSelected(nextLayer, fid,
                    (MapControl) CommenUtil.getMapControl(), centerPoint);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

		/*
         * added by 李忠义 20150620 设置下一层图层的点击事件，
		 */
        try {
            DataController dc = DataController.getInstance();
            // 获取TASK/Render.tcf 中的TaskLayer 标签的name值，作为输入参数
            targetLayer = dc.setActiveLayer(this.layer, null/* , true */);
            // 添加点选目标
            CommenUtil.StartTouchLong((IFeatureLayer) targetLayer, this, findViewById(R.id.contentArea), LOADMAPTYPE);
            // 刷新地图上的全部图层
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        CommenUtil.setZoomto(ev);
        // 最后刷一次即可
        CommenUtil.Refresh();

        //==================地图处理【完】========================

        navShow();
    }

    /**
     * 返回上一个  页面/层级
     */
    private void goBack() {

        selectListLayout.setVisibility(View.GONE);

        if (index == 0) { // 当前为第一层
            // 直接退出
            if (StringUtil.isFastDoubleClick(500)) {
                return;
            }
            // 清空
            Constants.selects.removeAll(Constants.selects);
            Constants.players.removeAll(Constants.players);
            Constants.positons.removeAll(Constants.positons);
            Constants.TargetXY = new double[2];

            finish();
            overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
        } else {
            //进度框提示
            Constants.DIALOG = MyLoadingDialog.createLoadingDialog(MapSelectActivity.this, "正在载入，请稍后...");
            Constants.DIALOG.show();
            if (index == Constants.nodelist.size() - 1 && Constants.dkBack) {//最后一层 且 缩放到了地块

                Constants.dkBack = false;
                mapBack();
            } else { // 返回上一层

                // 刷新数据
                if (index > 1) {
                    this.parent = Constants.selects.get(index - 2);
                } else {
                    this.parent = null;
                }

                if (Constants.selects.size() == index + 1) {
                    Constants.selects.remove(index);
                }
                Constants.selects.remove(index - 1);
                this.pLayer = Constants.players.get(index - 1);
                Constants.players.remove(index);
                this.position = Constants.positons.get(index - 1);
                Constants.positons.remove(index);
                index -= 1;

                navName = navName.substring(0, navName.lastIndexOf(" > "));
                title.setText(navName);
                int x = navName.lastIndexOf(" > ");
                if (x == -1) {
                    setTitle(navName.substring(0));
                } else {
                    setTitle(navName.substring(x + 3));
                }
                getData();
                adapter.setSelect(-1);
                adapter.refresh(levelList);

                //====================地图处理========================
                // 缩小地图回到上一级地图区域
                IEnvelope ev = Constants.envelopes.get(index);

                // 导航目标
                if (Constants.targets.get(index) != null) {
                    String[] ta = Constants.targets.get(index).split(",");
                    Constants.TargetXY[0] = Double.parseDouble(ta[0]);
                    Constants.TargetXY[1] = Double.parseDouble(ta[1]);

                    Constants.targets.remove(index + 1);
                } else {
                    Constants.TargetXY = new double[2];
                }

                if (index > 0) {
                    /**刷新高亮区域，使地图回退后可以点选*/
                    IFeatureLayer nextLayer = DataController.getInstance().getLayer(
                            this.pLayer);
                    IPoint centerPoint = null;
                    try {
                        if (CommenUtil.IsListSelected) {
                            centerPoint = nextLayer.getFeatureClass()
                                    .getGeometry(position).CenterPoint();
                        } else {
                            centerPoint = Constants.TargetPointTouch;
                        }
                        CommenUtil.setLightSelected(nextLayer, position,
                                (MapControl) CommenUtil.getMapControl(), centerPoint);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                //把layer fid都传对就OK了 设置选点选图层 added by 李忠义 20150626 设置下一层图层的点击事件，
                try {
                    DataController dc = DataController.getInstance();
                    // 获取TASK/Render.tcf 中的TaskLayer 标签的name值，作为输入参数
                    targetLayer = dc.setActiveLayer(this.layer, null/* , true */);
                    // 添加点选目标
                    CommenUtil.StartTouchLong((IFeatureLayer) targetLayer, this, findViewById(R.id.contentArea), LOADMAPTYPE);
                    // 刷新地图上的全部图层
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                CommenUtil.setZoomto(ev);
                CommenUtil.Refresh();

                //====================地图处理【完】========================

            }

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    StringUtil.dismissDialog(Constants.DIALOG);
                }
            }, 500);
        }

        navShow();

    }

    /**
     * 地图回退 从地块回退到村
     */
    private void mapBack() {

        //====================地图处理========================
        // 缩小地图回到上一级地图区域
        IEnvelope ev = Constants.envelopes.get(index);

        // 导航目标
        if (Constants.targets.get(index) != null) {
            String[] ta = Constants.targets.get(index).split(",");
            Constants.TargetXY[0] = Double.parseDouble(ta[0]);
            Constants.TargetXY[1] = Double.parseDouble(ta[1]);

            Constants.targets.remove(index + 1);
        } else {
            Constants.TargetXY = new double[2];
        }


        /**刷新高亮区域，使地图回退后可以点选*/
        IFeatureLayer nextLayer = DataController.getInstance().getLayer(
                this.pLayer);
        IPoint centerPoint = null;
        try {
            if (CommenUtil.IsListSelected) {
                centerPoint = nextLayer.getFeatureClass()
                        .getGeometry(position).CenterPoint();
            } else {
                centerPoint = Constants.TargetPointTouch;
            }
            CommenUtil.setLightSelected(nextLayer, position,
                    (MapControl) CommenUtil.getMapControl(), centerPoint);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //把layer fid都传对就OK了 设置选点选图层 added by 李忠义 20150626 设置下一层图层的点击事件，
        try {
            DataController dc = DataController.getInstance();
            // 获取TASK/Render.tcf 中的TaskLayer 标签的name值，作为输入参数
            targetLayer = dc.setActiveLayer(this.layer, null/* , true */);
            // 添加点选目标
            CommenUtil.StartTouchLong((IFeatureLayer) targetLayer, this, findViewById(R.id.contentArea), LOADMAPTYPE);
            // 刷新地图上的全部图层
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        CommenUtil.setZoomto(ev);
        CommenUtil.Refresh();
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        CommenUtil.getMap().setDeviceExtent(
                new Envelope(0, 0, CommenUtil.getMapControl().getWidth(),
                        CommenUtil.getMapControl().getHeight()));
        // added by lzy 20151120 在数据初始化前设置flag

        //刷新数据
        getData();
        adapter.refresh(levelList);
    }

    @Override
    public void onResume() {
        super.onResume();

        tv_GPSinfo = CommenUtil.getGPSInfo(getBaseContext());
        tv_GPSinfo.setTextColor(Color.BLACK);
        tv_GPSinfo.setBackgroundColor(Color.argb(128, 255, 255, 255));

        CommenUtil.getMapControl().addView(tv_GPSinfo,
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

        try {
            FactoryGPS factory = new FactoryGPS(tv_GPSinfo, null, null, null,
                    CommenUtil.getMapControl());
            FactoryGPS.NaviStart = false;
            factory.StartStopGPS(this, tv_GPSinfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 刷新图层
        CommenUtil.Refresh();
    }

    @Override
    protected void onPause() {
        super.onPause();
        CommenUtil.getMapControl().removeView(tv_GPSinfo);
    }


    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        taskName = getIntent().getStringExtra("taskName");
        periodCode = getIntent().getStringExtra("periodCode");
        periodLabel = getIntent().getStringExtra("periodLabel");
        navName = taskName;
        savaMark();
        // 保存当前层级的数据
        Constants.players.add(index, pLayer);
        Constants.positons.add(index, position);
        setTitle(navName);
        getView();
        mapView();
        StringUtil.dismissDialog(Constants.DIALOG);
        setmOnBackClickListener(new onBackClickListener() {
            @Override
            public void onBackClick() {
                goBack();
            }
        });
    }

    @Override
    protected void onDestroy() {
        new MSApplication().deleteActivity(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();
        }
        return true;
    }

    /**
     * 读取权限文件并验证
     *
     * @return
     */
    public boolean readFile() {
        String readPath = Environment.getExternalStorageDirectory()
                + "/Accredit/Authorization.txt";

        File idea = new File(readPath);
        // 判断文件是否存在
        if (!idea.exists()) {
            Toast.makeText(MapSelectActivity.this, "授权失败，请联系设备采购方\nTel：010-62202126", Toast.LENGTH_LONG)
                    .show();
            return false;
        }
        // 如果存在，判断文件中内容是否匹配
        else if (idea.exists()) {
            String str = getStr(readPath);
            if (string2MD5("password").equals(str)) {
                Toast.makeText(MapSelectActivity.this, "授权成功",
                        Toast.LENGTH_SHORT).show();
                return true;

            } else {
                Toast.makeText(MapSelectActivity.this, "授权失败，请联系设备采购方\n" +
                                "Tel：010-62202126",
                        Toast.LENGTH_LONG).show();
                return false;
            }
        }
        return false;
    }

    /**
     * 读取文件
     *
     * @param fileName
     * @return
     */
    public String getStr(String fileName) {
        try {
            FileInputStream in = new FileInputStream(new File(fileName));
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = reader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * MD5加码 生成32位md5码
     */
    public static String string2MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.map_select_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.gaodeNav:
                // 导航
                Intent gpsNaviIntent = new Intent(MapSelectActivity.this,
                        NaviMainActivity.class);
                gpsNaviIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(gpsNaviIntent);
                break;
            case R.id.lineNav:
                double endLon = Constants.TargetXY[1];
                double endLat = Constants.TargetXY[0];
                Intent intent = new Intent(MapSelectActivity.this, NaviLineActivity.class);
                intent.putExtra("endLon", endLon);
                intent.putExtra("endLat", endLat);
                startActivity(intent);
                break;
        }
        return true;
    }
}
